package com.wmz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmz.domain.SysUser;
import com.wmz.domain.SysUserRole;
import com.wmz.mapper.SysUserMapper;
import com.wmz.mapper.SysUserRoleMapper;
import com.wmz.service.SysUserRoleService;
import com.wmz.service.SysUserService;
import com.wmz.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 新增系统管理员
     * @return
     */
    @Override
    public int saveSysUser(SysUser sysUser) {
        // 新增系统管理员
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        // 密码加密
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        int count = sysUserMapper.insert(sysUser);
        // 新增管理员和角色的关系
        List<Long> roleIdList = sysUser.getRoleIdList();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() > 0) {
            // 获取新增的管理员ID
            Long userId = sysUser.getUserId();
            //遍历角色ID创建对象
            roleIdList.forEach(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                sysUserRoleList.add(sysUserRole);
            });
            // 批量保存
           sysUserRoleService.saveBatch(sysUserRoleList);
        }
        return count;
    }

    /**
     * 根据标识查询系统管理员信息
     * @param id 查询的管理员ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser querySysUserInfo(Long id) {
        // 查询管理员信息
        SysUser sysUser = sysUserMapper.selectById(id);
        // 查询管理员和角色对应集合
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id));
        //获取并设置角色id
        if(CollectionUtil.isNotEmpty(sysUserRoleList) && sysUserRoleList.size() > 0) {
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    /**
     * 修改管理员信息
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifySysUserInfo(SysUser sysUser) {
        // 修改管理员信息
        // 密码有值：修改（密码加密），密码无值：不变
        String newPassword = sysUser.getPassword();
        newPassword = StringUtils.hasText(newPassword) ? passwordEncoder.encode(newPassword):newPassword;
        sysUser.setPassword(newPassword);
        int count = sysUserMapper.updateById(sysUser);
        Long userId = sysUser.getUserId();
        // 修改管理员与角色关系
        // 先删除原有的关系
        if(count > 0) {
            sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId, userId));
            // 在添加新的关系
            List<Long> roleIdList = sysUser.getRoleIdList();
            if(CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() > 0) {
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量新增
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return count;
    }

    /**
     * 删除管理员
     * @param idList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeByIdList(Long[] idList) {
        // 先删除管理员信息
        boolean isRemove = false;
        int i = sysUserMapper.deleteBatchIds(Arrays.asList(idList));
        if(i > 0) {
            // 再删除管理员与角色的关系
            isRemove = sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
                    .in(SysUserRole::getUserId, idList));
        }

        return isRemove;
    }
}
